package com.ylyq.lingoserver.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {

    /**
     * 验证IP
     *
     * @return boolean
     * @author xianlin.tang
     * @date 2018年6月11日 上午10:13:27
     * @version 1.0.0
     */
    public static boolean isIP(String str) {
        boolean flag = false;
        try {
            Pattern regex = Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
            Matcher matcher = regex.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 生成UUID
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        if (uuid == null) {
            throw new NullPointerException("uuid is null");
        }
        String primaryKey = String.valueOf(uuid);
        if (StringUtils.isNotEmpty(primaryKey) && primaryKey.contains("-")) {
            primaryKey = primaryKey.replaceAll("-", "");
        }
        return primaryKey;
    }

    // 随机字符串生成
    public static String getRandomString(int length) { // length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getUUID());
    }

    /**
     * 生成APP访问令牌，采用MD5
     *
     * @return APP访问令牌
     */
    synchronized public static String getToken() {
        // 获取UUID
        String uuid = UUID.randomUUID().toString();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (StringUtils.isNotEmpty(uuid)) {
                md.update(uuid.getBytes());
            }
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 把字节转换为16进制
     *
     * @param data
     *            待处理数据
     * @return
     */
    public static String toHex(final byte[] data) {
        String result = "";
        if (data != null && data.length > 0) {
            StringBuilder sb = new StringBuilder();
            for (byte b : data) {
                sb.append(String.format("%02X", b));
            }
            result = sb.toString();
        }
        return result;
    }

    /**
     * json数组排序
     * @param lstObj
     * @param field
     * @param isAsc
     */
    public static void sort(List<JSONObject> lstObj, final String field, boolean isAsc) {
        Collections.sort(lstObj, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                Object f1 = o1.get(field);
                Object f2 = o2.get(field);
                return f1.toString().compareTo(f2.toString());
            }
        });
        if (!isAsc) {
            Collections.reverse(lstObj);
        }
    }

    /**
     * @Author xiaweichao
     * @Description //TODO String[]转换Long[] * @Date 17:31 2020/7/3
     * @Param [stringArray]
     * @return java.lang.Long[]
     **/
    public static Long[] StringArray2LongArray(String[] stringArray)
    {
        List<Long> list=new ArrayList<>();
        for (String str: stringArray) {
            try {
                list.add(Long.parseLong(str));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        Long[] longArray=list.toArray(new Long[list.size()]);
        return longArray;
    }

    /*
     * @Author xiaweichao
     * @Description //获取当前时间，不带—— ：/  用于给上传文件时重命名文件名
     * @Param []
     * @return java.lang.String
     **/
    public static String getCurrentDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        return df.format(new Date());
    }

}
